package com.tingyuge.base.jdk.io.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * @Created by xiaodao
 */
public class AioClientWriteHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;
    private  CountDownLatch latch;
    public AioClientWriteHandler(AsynchronousSocketChannel clientChannel, CountDownLatch latch) {
    this.clientChannel = clientChannel;
    this.latch = latch;
    }


    @Override
    public void completed(Integer result, ByteBuffer byteBuffer) {
        if(byteBuffer.hasRemaining()){//没有写完
            clientChannel.write(byteBuffer,byteBuffer,this);
        }else{
            //读取数据
            //读取数据
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            //异步的读
            clientChannel.read(readBuffer,readBuffer,new AioClientReadHandler(clientChannel, latch));


        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.err.println("数据发送失败");
        try {
            clientChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }
}
